/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年7月18日
 */
package com.massyframework.beanskin.service.adapt;

import java.util.List;

import com.massyframework.beanskin.service.ServiceRepository;

/**
 * 通过服务资源库实现{@link Adaptable}的抽象类
 * @author huangkh
 *
 */
public abstract class AdaptObject implements Adaptable {

	private transient AdaptObjectFactoryRepository adaptObjectFactoryRepository;
	/**
	 * 
	 */
	public AdaptObject() {
		
	}

	@Override
	public <A> A adapt(Class<A> adaptType) {
		if (this.getServiceRepository() == null) return null;
		
		return this.doAdaptWithServiceRepository(adaptType);
	}
	
	/**
	 * 使用ServiceRepository进行适配
	 * @param <A>
	 * @param adaptType {@link Class},要适配的类型
	 * @return {@link A}
	 */
	protected <A> A doAdaptWithServiceRepository(Class<A> adaptType) {
		AdaptObjectFactoryRepository repo = this.getAdaptObjectFactoryRepositroy();
		if (repo == null) return null;
		
		List<AdaptObjectFactory<A>> factories =
				repo.getAdaptObjectFactories(adaptType, this.getClass());
		for (AdaptObjectFactory<A> factory: factories) {
			A result = factory.createAdaptObject(this, adaptType);
			if (result != null) {
				return result;
			}
		}
		
		return null;
	}
	
	
	/**
	 * 服务资源库
	 * @return {@link ServiceRepository}
	 */
	protected abstract ServiceRepository getServiceRepository();
	
	/**
	 * 获取适配对象工厂资源库
	 * @return {@link AdaptObejctFactoryRepository}
	 */
	protected AdaptObjectFactoryRepository getAdaptObjectFactoryRepositroy() {
		if (this.adaptObjectFactoryRepository == null) {
			ServiceRepository repo = this.getServiceRepository();
			this.adaptObjectFactoryRepository = repo.findService(AdaptObjectFactoryRepository.class).orElse(null);
		}
		
		return this.adaptObjectFactoryRepository;
	}
}
